<template>
  <div class="visitor_statistics">

    <div class="tips">
      操作说明
      <a-tooltip placement="right">
        <template #title>
          <span>访客所使用的网络设备情况。可作为网站设计的参考，从而有效提升访客的网站交互体验。</span>
        </template>
        <span class="iconfont icon-hint1"></span>
      </a-tooltip>
    </div>
    <div class="selectSite">
      <getSite @handleChange="handleChange" ref="getSite_ref"></getSite>
    </div>
    <div class="visitDetail">
      <div class="visitDetail_header">

        <div class="timeSelect item">
          <!-- 所属时间模块部分 -->
          <commonDatePick :formData='formData' @select-type="selectType" @selectTimeChange="selectTimeChange" ref="commonDatePick_ref"></commonDatePick>
        </div>

        <div class="option-content">
          <!-- <a-button @click="resetOptions">重置</a-button> -->
          <!-- <a-button :style="{ 'margin-right': '8px' }" class="addButton" type="primary"
            @click="getNetworkDevices()">搜索</a-button> -->
        </div>
      </div>
      <div class="tendency_statistics_charts">
        <div class="scrollSection">
          <div class="charts">
            <div class="pv_uvlists">
              <div class="tendency_statistics_item">
                <div class="selectTypes">
                  <span>显示指标：</span>
                  <a-radio-group v-model:value="showOptionsSelected"
                    :options="showOptions.map((item: any) => ({ value: item.value, label: item.label }))"
                    @change="handleChange_select" />
                </div>
              </div>
            </div>
            <div class="tendencyOnlinePie_line">
              <div id="chart_bar"></div>
            </div>
          </div>
          <!-- 表格展示部分 -->
          <baseTable :columns="columns.visitorStatistics.netWork" :dataSource="tableData" :isSelect="true" :scroll="scroll"
            ref="sensitiveBaseTables" :isShowPagination="isShowPagination" :rowSelection="1" :total="configData.total"
            :indentSize="60">

            <template #bodyCell="{ column, text, record }">
              <template v-if="column.ellipsis">
                <table-tool-tip :text="text" :column="column"></table-tool-tip>
              </template>
              <template v-if="column.dataIndex == 'sourceUrl'">
                <a class="sourceUrl">{{ text }}</a>
              </template>

            </template>
            <template #expandedRowRender="{ record }">
              <div class="innerTable">
                <a-table :dataSource="record.childs" :columns="columns.visitorStatistics.netWorkInner" :show-header="false"
                  :pagination="false" />
              </div>

            </template>
          </baseTable>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, nextTick, onMounted, onBeforeMount, onUnmounted, reactive, watch, computed } from "vue";
import request from "@/api/index";
import getters from "@/store/getters";
import { initEcharts } from "@/components/echarts/index";
import { optionBar } from "./echartType/options";
import columns from "@/components/table/tableConfig/tableColumn/siteStatistics";
import baseTable from "@/components/table/baseTable.vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import commonDatePick from '../commonHeader/date.vue';
import getSite from '../commonHeader/getSite.vue';
import {randomWord, transverterMss} from '@/utils/common'
import { number } from "echarts";
// type flowColumns
interface dataSourceType {
  [propName: string]: any;
}
//getters
const userInfo = getters.userInfo();
//data
const sectionValue = ref(userInfo.siteId);
const tableData = ref<dataSourceType[]>([])

const dataSource = ref<dataSourceType>(JSON.parse(JSON.stringify(optionBar)));
dataSource.value.legend.data = ['移动设备', '计算机'];

const showOptionsSelected = ref(1);
const showOptions = ref(
  [
    { label: '浏览量(PV)', value: 1 },
    { label: '访问数(UV)', value: 2 },
    { label: 'IP数', value: 3 },
  ]
);
const getSite_ref = ref();
//图表展示

const commonDatePick_ref = ref();
let selectTimeRange = ref<(string | number)[]>([]); //选择时间范围
let seleType_label = ref('pvTypeTypeNumDto');
const dataSource_remote = ref<dataSourceType>({})
//表格数据
let configData = reactive<dataSourceType>({ total: 0, size: 10, records: [] });
let scroll: dataSourceType = reactive({ y: 200, isFixed: false }); // 表单滚动设置
const isShowPagination = false; // 是否需要配分页器


const formData = reactive<dataSourceType>({
  selectTimeOption: 1,
  TimeOptions: [{
    label: '今天',
    value: 1
  }, {
    label: '昨天',
    value: 2
  }, {
    label: '最近7天',
    value: 3
  }, {
    label: '最近30天',
    value: 4
  }],
})
let selectAreaData = ref(null); // 选择区域
const getArea_ref = ref();


// computed
selectAreaData = computed(() => getArea_ref.value?.selectAreaData || null);
seleType_label = computed(() => showOptionsSelected.value == 1 ? 'pvTypeNumDtoList' :
  showOptionsSelected.value == 2 ? 'uvTypeNumDtoList' : 'ipTypeNumDtoList')
//methods
const handleChange = (value: any) => {//其他选择变化
  nextTick(() => {
    getNetworkDevices();
  });
};
const selectTimeChange = () => {
  selectTimeRange.value = commonDatePick_ref.value.selectTimeRange;
  getNetworkDevices();
}
// 获取在线统计数据
const getNetworkDevices = async () => {
  sectionValue.value = getSite_ref.value.sectionValue;
  selectTimeRange.value = commonDatePick_ref.value.selectTimeRange;
  nextTick(async () => {
    let data: dataSourceType = {
      siteId: sectionValue.value,
      startTime: selectTimeRange.value[0],
      endTime: selectTimeRange.value[1],
      province: selectAreaData.value,
      sourceUrlType: formData.fromSectionValue
    }
    await request.getNetworkDevices(data).then((res: dataSourceType) => {
      dataSource_remote.value = res;
      tableData.value = res.excelListDto;
      let obj:dataSourceType=res.nameSubListMap;
      for(let i in obj){
        // console.log(i, '222')
        obj[i].forEach((item:any)=>{
          item.id = randomWord(false, 4,4);
        })
      }
      let keys = Object.keys(obj);
      
      tableData.value.forEach((item:any, index:number)=>{
         item.id= randomWord(false, 4,4);
         item.childs = obj[keys[index]];
         item.index = index+1;
         item.bounceRate = (item.bounceRate * 100).toFixed() + '%'
         item.averageVisitLength = transverterMss(item.averageVisitLength)
        //  console.log(item);
         if(item.childs) {
          console.log(item.childs);
          for(let i2 in item.childs) {
            item.childs[i2].bounceRate = (item.childs[i2].bounceRate * 100).toFixed() + '%'
            item.childs[i2].averageVisitLength = transverterMss(item.childs[i2].averageVisitLength)
          }
         }
         
      })
    });
    nextTick(() => {
      setData()
    })
  })

}


//选择搜索项
const selectType = (item: dataSourceType, type: string) => {
  formData[type] = item.value;

  nextTick(() => {
    getNetworkDevices();
  })
}
const handleChange_select = () => {
  nextTick(() => {
    setData()
  })
}
const setData = () => {
  let res = dataSource_remote.value;
  // console.log(res);
  
  let name = showOptionsSelected.value == 1 ? '浏览量(PV)' : showOptionsSelected.value == 2 ? '访问数(UV)' : 'IP数';
  dataSource.value.xAxis[0].data = ['移动设备', '计算机'];
  dataSource.value.series = [{
    name: name,
    type: 'bar',
    barWidth: '40',
    data: res[seleType_label.value] && res[seleType_label.value].length > 0 ? [res[seleType_label.value][1].typeNum, res[seleType_label.value][0].typeNum] : [0, 0]
  }]
  initEcharts('chart_bar', dataSource.value);
}

//onMounted

onMounted(() => {
  getNetworkDevices();

});

</script>

<style lang="less" scoped>
.visitor_statistics {
  width: 100%;
  height: calc(100% - 72px);
  padding: 16px;
  background: #fff;
  overflow: auto;

  .tips {
    margin-bottom: 24px;
    font-size: 14px;
    color: #333;
  }

  .visitDetail {
    .visitDetail_header {
      display: flex;
      flex-wrap: wrap;
      position: relative;
      width: 90%;
      padding-top: 24px;

      .from {
        font-size: 14px;
        color: #333;
      }

      .timeSelect {
        margin-right: 24px;
      }

      .item {
        height: 40px;
        margin-right: 24px;
        margin-bottom: 24px;
      }

      .ant-select {
        width: 100px;
      }

      .option-content {
        position: absolute;
        right: -10%;
        display: flex;
        top: 18px;
        align-items: center;
        font-size: 14px;
      }
    }

    .charts {
      width: 100%;
      height: 350px;
      border: 1px solid #e8e8e8;
      border-radius: 4px;
      padding: 24px;
      margin-bottom: 24px;

      #chart_bar {
        width: 100%;
        height: 350px;
      }
    }
  }
}
</style>
<style lang="scss">
.visitDetail {
  .options {
    display: flex;
    align-items: center;
    font-size: 14px;

    .options_label {
      margin-right: 12px;
    }

    .options_content {
      margin-right: 12px;
      border: 1px solid var(--theme_button_bg_color, #1F6DED);
      display: flex;
      border-radius: 4px;

      span {
        padding: 4px 14px;
        color: #333;
        border-right: 1px solid var(--theme_button_bg_color, #1F6DED);
      }

      span:nth-last-of-type(1) {
        border-right: none;
      }

      span:hover {
        background: var(--theme_button_hover_bg_color, #4892fa);
        border-color: var(--theme_button_hover_bg_color, #4892fa);
        color: #fff;
      }

      .activeOption {
        color: #fff;
        background: var(--theme_button_bg_color, #1F6DED);
      }
    }
  }
}
</style>
<style lang="scss">
.visitor_statistics {
  .ant-table-thead .ant-table-cell:nth-last-of-type(1) {
    text-align: left;
    margin-right: 16px;
  }

  .ant-table-cell {
    .ant-table-row-expand-icon {
      border: none;
      background: transparent;
    }
  }

  .ant-table-expanded-row {
    .ant-table-cell:nth-of-type(1) {
      padding: 0
    }
  }

  .innerTable {

    .ant-table-cell:nth-child(1) {
      padding-left: 64px !important;
    }


  }

  .ant-table-column-sorters {
    max-width: 100px;
  }
}
</style>